import { useState } from "react";

interface Product {
  id: number;
  name: string;
  count: number;
}

const initialProducts: Product[] = [
  { id: 1, name: "Product 1", count: 10 },
  { id: 2, name: "Product 2", count: 20 },
  { id: 3, name: "Product 3", count: 30 }
];

function ShoppingCart() {
  const [products, setProducts] = useState<Product[]>(initialProducts);

  function handleIncreaseClick(productId: number) {
    const newProducts = products.map(product => {
      if (product.id === productId) {
        return { ...product, count: product.count + 1 };
      }
      return product;
    });
    setProducts(newProducts);
  }

  /**
   * 删除商品的count计数
   * 如果count为0，则删除这一项
   * @param productId 购物车商品的id
   */
  function handleDecreaseClick(productId: number) {
    const newProducts = products
      .map(product => {
        if (product.id === productId) {
          return { ...product, count: product.count - 1 };
        }
        return product;
      })
      .filter(item => item.count > 0);

    setProducts(newProducts);
  }

  return (
    <ul>
      {products.map(product => (
        <li key={product.id}>
          {product.name}
          &nbsp;
          <b>{product.count}</b>
          &nbsp;
          <button onClick={() => handleIncreaseClick(product.id)}>+</button>
          &nbsp;
          <button onClick={() => handleDecreaseClick(product.id)}>-</button>
        </li>
      ))}
    </ul>
  );
}

export default ShoppingCart;
